<script setup>
import { ref, onMounted, watch, computed } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close'])

// API 基础URL
const API_BASE_URL = 'http://localhost:5000/api'

// 用户列表
const users = ref([])
const isLoading = ref(false)
const errorMessage = ref('')

// 搜索相关
const searchQuery = ref('')
const searchField = ref('username') // 搜索字段：username, email, role
const filteredUsers = computed(() => {
  if (!searchQuery.value) return users.value
  
  const query = searchQuery.value.toLowerCase()
  return users.value.filter(user => {
    switch (searchField.value) {
      case 'username':
        return user.username.toLowerCase().includes(query)
      case 'email':
        return user.email && user.email.toLowerCase().includes(query)
      case 'role':
        const roleText = user.role === 'admin' ? '管理员' : '普通用户'
        return roleText.toLowerCase().includes(query)
      default:
        return true
    }
  })
})

// 编辑用户相关
const isEditing = ref(false)
const editingUser = ref(null)
const editUsername = ref('')
const editEmail = ref('')
const editRole = ref('user')
const editPassword = ref('') // 新增：用于存储编辑时的新密码

// 添加用户相关
const isAdding = ref(false)
const newUsername = ref('')
const newPassword = ref('')
const newEmail = ref('')
const newRole = ref('user')

// 获取所有用户
const fetchUsers = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    isLoading.value = true
    errorMessage.value = ''
    
    const response = await fetch(`${API_BASE_URL}/admin/users`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('获取用户列表失败')
    }
    
    const data = await response.json()
    users.value = data
  } catch (error) {
    console.error('Error fetching users:', error)
    errorMessage.value = error.message || '获取用户列表失败'
  } finally {
    isLoading.value = false
  }
}

// 删除用户
const deleteUser = async (userId) => {
  if (!confirm('确定要删除此用户吗？此操作不可撤销。')) return
  
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    isLoading.value = true
    errorMessage.value = ''
    
    const response = await fetch(`${API_BASE_URL}/admin/users/${userId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('删除用户失败')
    }
    
    // 从列表中移除
    users.value = users.value.filter(user => user.id !== userId)
  } catch (error) {
    console.error('Error deleting user:', error)
    errorMessage.value = error.message || '删除用户失败'
  } finally {
    isLoading.value = false
  }
}

// 开始编辑用户
const startEdit = (user) => {
  editingUser.value = user
  editUsername.value = user.username
  editEmail.value = user.email
  editRole.value = user.role
  editPassword.value = '' // 新增：重置密码字段
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  editingUser.value = null
}

// 保存编辑
const saveEdit = async () => {
  if (!editingUser.value) return
  
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    isLoading.value = true
    errorMessage.value = ''
    
    let updatedUser;
    
    // 如果只修改密码，不修改其他信息
    if (editPassword.value && editUsername.value === editingUser.value.username && 
        editEmail.value === editingUser.value.email && editRole.value === editingUser.value.role) {
      // 只更新密码
      const passwordResponse = await fetch(`${API_BASE_URL}/admin/users/${editingUser.value.id}/password`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          password: editPassword.value
        })
      })
      
      if (!passwordResponse.ok) {
        throw new Error('更新密码失败')
      }
      
      // 使用现有用户信息
      updatedUser = editingUser.value
    } else {
      // 更新用户基本信息
      const response = await fetch(`${API_BASE_URL}/admin/users/${editingUser.value.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          username: editUsername.value,
          email: editEmail.value,
          role: editRole.value
        })
      })
      
      if (!response.ok) {
        throw new Error('更新用户信息失败')
      }
      
      // 如果同时也需要更新密码
      if (editPassword.value) {
        const passwordResponse = await fetch(`${API_BASE_URL}/admin/users/${editingUser.value.id}/password`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            password: editPassword.value
          })
        })
        
        if (!passwordResponse.ok) {
          throw new Error('更新密码失败')
        }
      }
      
      updatedUser = await response.json()
    }
    
    // 更新本地列表
    const index = users.value.findIndex(u => u.id === editingUser.value.id)
    if (index !== -1) {
      users.value[index] = updatedUser
    }
    
    // 关闭编辑模式
    isEditing.value = false
    editingUser.value = null
    editPassword.value = '' // 清空密码字段
  } catch (error) {
    console.error('Error updating user:', error)
    errorMessage.value = error.message || '更新用户失败'
  } finally {
    isLoading.value = false
  }
}

// 开始添加用户
const startAddUser = () => {
  isAdding.value = true
  newUsername.value = ''
  newPassword.value = ''
  newEmail.value = ''
  newRole.value = 'user'
}

// 取消添加
const cancelAdd = () => {
  isAdding.value = false
}

// 保存新用户
const saveNewUser = async () => {
  if (!newUsername.value || !newPassword.value || !newEmail.value) {
    errorMessage.value = '请填写所有必填字段'
    return
  }
  
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    isLoading.value = true
    errorMessage.value = ''
    
    const response = await fetch(`${API_BASE_URL}/admin/users`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        username: newUsername.value,
        password: newPassword.value,
        email: newEmail.value,
        role: newRole.value
      })
    })
    
    if (!response.ok) {
      throw new Error('添加用户失败')
    }
    
    // 添加到列表
    const newUser = await response.json()
    users.value.push(newUser)
    
    // 关闭添加模式
    isAdding.value = false
  } catch (error) {
    console.error('Error adding user:', error)
    errorMessage.value = error.message || '添加用户失败'
  } finally {
    isLoading.value = false
  }
}

// 组件挂载时获取用户列表
onMounted(() => {
  if (props.visible) {
    fetchUsers()
  }
})

// 监听visible属性变化
watch(() => props.visible, (newValue) => {
  if (newValue) {
    fetchUsers()
  }
})
</script>

<template>
  <div v-if="visible" class="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50">
    <div class="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-6 w-[800px] max-h-[80vh] relative glass scale-in">
      <button class="absolute right-4 top-4 text-gray-400 hover:text-gray-600" @click="$emit('close')">
        <i class="fas fa-times"></i>
      </button>
      
      <h2 class="text-xl font-bold mb-5 text-gradient-purple">后台管理系统</h2>
      
      <!-- 错误消息 -->
      <div v-if="errorMessage" class="bg-red-50 text-red-500 p-3 rounded-lg mb-4">
        {{ errorMessage }}
      </div>
      
      <!-- 加载状态 -->
      <div v-if="isLoading" class="flex justify-center my-8">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
      
      <!-- 用户管理界面 -->
      <div v-else>
        <!-- 搜索和添加用户区域 -->
        <div class="mb-4 flex items-center justify-between gap-4">
          <!-- 搜索区域 -->
          <div class="flex-1 flex items-center gap-2">
            <div class="relative flex-1">
              <input 
                v-model="searchQuery" 
                type="text" 
                placeholder="搜索用户..." 
                class="w-full px-4 py-2 pr-10 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 bg-white/80"
              >
              <i class="fas fa-search absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            </div>
            <select 
              v-model="searchField"
              class="px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 bg-white/80"
            >
              <option value="username">用户名</option>
              <option value="email">邮箱</option>
              <option value="role">角色</option>
            </select>
          </div>
          
          <!-- 添加用户按钮 -->
          <button 
            @click="startAddUser" 
            class="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg hover:from-green-600 hover:to-emerald-700 transition-all duration-300 flex items-center gap-2"
          >
            <i class="fas fa-plus"></i>
            <span>添加用户</span>
          </button>
        </div>
        
        <!-- 用户列表 -->
        <div class="overflow-y-auto max-h-[60vh]">
          <table class="min-w-full bg-white/50 rounded-lg overflow-hidden">
            <thead class="bg-gray-100/80">
              <tr>
                <th class="py-3 px-4 text-left">用户名</th>
                <th class="py-3 px-4 text-left">邮箱</th>
                <th class="py-3 px-4 text-left">角色</th>
                <th class="py-3 px-4 text-right">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in filteredUsers" :key="user.id" class="border-t border-gray-100 hover:bg-blue-50/50 transition-colors">
                <td class="py-3 px-4">{{ user.username }}</td>
                <td class="py-3 px-4">{{ user.email }}</td>
                <td class="py-3 px-4">
                  <span 
                    :class="[
                      'px-2 py-1 rounded-full text-xs font-medium', 
                      user.role === 'admin' ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'
                    ]"
                  >
                    {{ user.role === 'admin' ? '管理员' : '普通用户' }}
                  </span>
                </td>
                <td class="py-3 px-4 text-right">
                  <button 
                    @click="startEdit(user)" 
                    class="text-blue-600 hover:text-blue-800 mr-3"
                    title="编辑"
                  >
                    <i class="fas fa-edit"></i>
                  </button>
                  <button 
                    @click="deleteUser(user.id)" 
                    class="text-red-600 hover:text-red-800"
                    title="删除"
                  >
                    <i class="fas fa-trash"></i>
                  </button>
                </td>
              </tr>
              <tr v-if="filteredUsers.length === 0">
                <td colspan="4" class="py-8 text-center text-gray-500">
                  {{ searchQuery ? '没有找到匹配的用户' : '暂无用户数据' }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- 编辑用户弹窗 -->
      <div v-if="isEditing" class="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-60">
        <div class="bg-white rounded-xl shadow-xl p-6 w-96 relative">
          <h3 class="text-lg font-bold mb-4">编辑用户</h3>
          <form @submit.prevent="saveEdit" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
              <input 
                v-model="editUsername" 
                type="text" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
                required
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
              <input 
                v-model="editEmail" 
                type="email" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
                required
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">角色</label>
              <select 
                v-model="editRole" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
              >
                <option value="user">普通用户</option>
                <option value="admin">管理员</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">新密码（留空表示不修改）</label>
              <input 
                v-model="editPassword" 
                type="password" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
                placeholder="输入新密码"
              >
            </div>
            <div class="flex justify-end gap-3">
              <button 
                type="button"
                @click="cancelEdit"
                class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
              >
                取消
              </button>
              <button 
                type="submit"
                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                保存
              </button>
            </div>
          </form>
        </div>
      </div>
      
      <!-- 添加用户弹窗 -->
      <div v-if="isAdding" class="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-60">
        <div class="bg-white rounded-xl shadow-xl p-6 w-96 relative">
          <h3 class="text-lg font-bold mb-4">添加用户</h3>
          <form @submit.prevent="saveNewUser" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
              <input 
                v-model="newUsername" 
                type="text" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
                required
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
              <input 
                v-model="newPassword" 
                type="password" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
                required
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
              <input 
                v-model="newEmail" 
                type="email" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
                required
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">角色</label>
              <select 
                v-model="newRole" 
                class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400"
              >
                <option value="user">普通用户</option>
                <option value="admin">管理员</option>
              </select>
            </div>
            <div class="flex justify-end gap-3">
              <button 
                type="button"
                @click="cancelAdd"
                class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
              >
                取消
              </button>
              <button 
                type="submit"
                class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
              >
                添加
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.glass {
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.scale-in {
  animation: scaleIn 0.3s ease-out forwards;
}

@keyframes scaleIn {
  from {
    transform: scale(0.9);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

/* 自定义滚动条 */
.overflow-y-auto {
  scrollbar-width: thin;
  scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
}

.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.5);
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background-color: rgba(156, 163, 175, 0.7);
}
</style> 